package com.mc.moring.information.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.mc.moring.R;
import com.mc.moring.app.LogUtils;
import com.mc.moring.base.BaseApplication;
import com.mc.moring.base.BaseFragment;
import com.mc.moring.base.HttpCallback;
import com.mc.moring.base.SaveZiLiPageTool;
import com.mc.moring.bean.SingleSelectBean;
import com.mc.moring.bean.ZiLiPageUserDataBean;
import com.mc.moring.event.UpdateUserEvent;
import com.mc.moring.information.CapitalInforActivity;
import com.mc.moring.information.modle.KycModle;
import com.mc.moring.main.MainActivity;
import com.mc.moring.main.modle.LoanModle;
import com.mc.moring.util.PointMgr;
import com.mc.moring.util.T;
import com.mc.moring.util.ToastUtils;
import com.mc.moring.widge.InformationConfirmarDialog;
import com.mc.moring.widge.SingleSelectDialogView;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LinkAccountFragment extends BaseFragment {

    CapitalInforActivity activity;
    TextView tv_su_to;
    LinearLayout ll_bank_name;
    TextView tv_bank_name;
    FrameLayout fl_bank_name;
    TextView et_bank_name;
    TextView tv_bank_name_err;
    View bank_line;
    LinearLayout ll_account_number;
    TextView tv_account_number;
    EditText et_account_number;
    TextView tv_account_number_err;
    View number_line;
    TextView tv_account_number_tip;
    private String editString = "";

//    TextView tv_tip;

//    LinearLayout lly_bottom_tips;

    LinearLayout ll_account_type;
    TextView tv_account_type;
    FrameLayout fl_account_type;
    TextView et_account_type;
    private JSONArray bankJa;
    private JSONObject selectBank;
    public KycModle kycModle = null;
    String bankCode, mNationalId;
    String accountType = "3";
    View view = null;
    private CapitalInforActivity fatherActivity;

    public interface ActivityListener{
        public void sendValue(String value);
    }

    private ActivityListener activityListener;


    public LinkAccountFragment(Activity activity) {
        this.activity = (CapitalInforActivity) activity;
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        fatherActivity = (CapitalInforActivity) activity;
        activityListener = (ActivityListener) getActivity();
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        LogUtils.logE("page 4");
        PointMgr.INSTANCE.sendEvent("bank_account_info_yes");
        Log.e("PointMgr.INSTANCE.sendEvent", "bank_account_info_yes");
        view = inflater.inflate(R.layout.fragment_link_account, container, false);
        kycModle = KycModle.Companion.getInstant();
        initView();
        initData();
        return view;
    }

    @Override
    public void initView() {
        tv_su_to = view.findViewById(R.id.tv_sub_to);

        ll_bank_name = view.findViewById(R.id.ll_bank_name);
        tv_bank_name = view.findViewById(R.id.tv_bank_name);
        et_bank_name = view.findViewById(R.id.et_bank_name);
        fl_bank_name = view.findViewById(R.id.fl_bank_name);
        tv_bank_name_err = view.findViewById(R.id.tv_bank_name_err);
        bank_line = view.findViewById(R.id.bank_line);

        ll_account_number = view.findViewById(R.id.ll_account_number);
        tv_account_number = view.findViewById(R.id.tv_account_number);
        et_account_number = view.findViewById(R.id.et_account_number);
        tv_account_number_err = view.findViewById(R.id.tv_account_number_err);
        number_line = view.findViewById(R.id.number_line);
        tv_account_number_tip = view.findViewById(R.id.tv_account_number_tip);
//        et_account_number.addTextChangedListener(new CommonTextWatcher(et_account_number, tv_account_number_err));

//        tv_tip = view.findViewById(R.id.tv_tip);

//        lly_bottom_tips = view.findViewById(R.id.lly_bottom_tips);

        ll_account_type = view.findViewById(R.id.ll_account_type);
        tv_account_type = view.findViewById(R.id.tv_account_type);
        fl_account_type = view.findViewById(R.id.fl_account_type);
        et_account_type = view.findViewById(R.id.et_account_type);

        et_account_type.setText("RUT");
        accountType = "3";
        et_bank_name.setText("Banco Estado (Banco del Estado de Chile)");
        setDefaultBankCode();
        et_account_number.setInputType(InputType.TYPE_CLASS_TEXT);
        getZiLiPageUserFullInfo(true);

        et_account_number.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                PointMgr.INSTANCE.sendEvent("cl_xuanz_yh_name_3");
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_3");
            }
        });
        et_account_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {}

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Log.e("----char",charSequence.toString());
                if ( et_account_type.getText().toString().equals("RUT") ){
                    if ( charSequence.length() >= 7 ){
                        tv_account_number_err.setVisibility(View.GONE);
                        number_line.setBackgroundColor(Color.parseColor("#33000000"));
                    }
                } else {
                    if ( charSequence.length() >= 8 ){
                        tv_account_number_err.setVisibility(View.GONE);
                        number_line.setBackgroundColor(Color.parseColor("#33000000"));
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

                if (s.toString().matches(".*[\u4e00-\u9fa5].*")) {
                    et_account_number.setText(s.toString().replaceAll(".*[\u4e00-\u9fa5].*", editString));
                    et_account_number.setSelection(et_account_number.getText().length()); // 设置光标位置
                } else {
                    editString = s.toString();
                }
            }
        });

        tv_su_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointMgr.INSTANCE.sendEvent("cl_xuanz_yh_name_4");
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_4");
                hideErrTips();
                if (TextUtils.isEmpty(bankCode)) {
                    tv_bank_name_err.setVisibility(View.VISIBLE);
                    bank_line.setBackgroundColor(Color.parseColor("#4DFF3737"));
                    return;
                }
                String accountStr = et_account_number.getText().toString();
                Log.e("----accountStr",accountStr);
                String account_type = et_account_type.getText().toString();
                Log.e("----account_type", account_type);
                if (account_type != null) {
                    if (account_type.equals("Cuenta ahorro") || account_type.equals("Cuenta corriente")
                            || account_type.equals("Vista")) {
                        if (!verificationBankAccountBase(8,20, accountStr)) {
                            tv_account_number_err.setVisibility(View.VISIBLE);
                            tv_account_number_err.setText("Error, introduzca un número puro de 8 - 20 dígitos");
                            number_line.setBackgroundColor(Color.parseColor("#4DFF3737"));

                            Log.e("----","002");
                            return;
                        } else {
                            tv_account_number_err.setVisibility(View.GONE);
                            number_line.setBackgroundColor(Color.parseColor("#33000000"));
                            Log.e("----","01");
                        }
                    } else if (account_type.equals("RUT")) {

                        if (accountStr.length()<7 ||accountStr.length() >9) {
                            tv_account_number_err.setVisibility(View.VISIBLE);
                            tv_account_number_err.setText("Error, introduzca un número puro de 7 - 9 dígitos");
                            number_line.setBackgroundColor(Color.parseColor("#4DFF3737"));
                            Log.e("----","004");
                            return;
                        } else {
                            tv_account_number_err.setVisibility(View.GONE);
                            number_line.setBackgroundColor(Color.parseColor("#33000000"));
                            Log.e("----","02");
                        }
                    }
                } else {
                    tv_account_number_err.setText("Por favor, elija nombre bancaria");
                    tv_account_number_err.setVisibility(View.VISIBLE);
                    number_line.setBackgroundColor(Color.parseColor("#4DFF3737"));
                    Log.e("----","005");
                    return;
                }
                InformationConfirmarDialog myDialog = new InformationConfirmarDialog(getActivity(), et_account_number.getText().toString().trim());
                myDialog.setDialogViewOnClickListener(new InformationConfirmarDialog.DialogViewOnClickListener() {
                    @Override
                    public void onClickConfirm() {
                        myDialog.dismiss();
                        dealWithSubData();
                    }

                    @Override
                    public void onClickCancel() {
                        myDialog.dismiss();
//                                                        goMain(data);
                    }
                });
                myDialog.showToPermissionSettingDialog(getActivity());
            }
        });
        fl_account_type.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                close();
                PointMgr.INSTANCE.sendEvent("cl_xuanz_yh_name_2");
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_2");
                selectZiLiPageTipoDeCuenta();
                tv_account_number_err.setVisibility(View.GONE);
                number_line.setBackgroundColor(Color.parseColor("#33000000"));
                if (et_account_type.getText().equals("RUT") &&
                        et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
                    tv_account_number_tip.setVisibility(View.VISIBLE);
                    tv_account_number_tip.setText("\nPara garantizarquelacuenta receptora sea consistente con la persona concédula de identidad, la cuenta RUT no admite modificación, se puede elegir otra cuenta bancaria para recibir el pago.");
                    tv_account_number_tip.setTextColor(Color.parseColor("#FFB307"));
                    Log.e("----","006");
                } else {
                    tv_account_number_tip.setVisibility(View.GONE);
                }
            }
        });

        fl_bank_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PointMgr.INSTANCE.sendEvent("cl_xuanz_yh_name_1");
                Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_1");
                close();
                getZiLiPagePayBankList();
                tv_account_number_err.setVisibility(View.GONE);
                number_line.setBackgroundColor(Color.parseColor("#33000000"));
                if (et_account_type.getText().equals("RUT") &&
                        et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
                    tv_account_number_tip.setVisibility(View.VISIBLE);
                    tv_account_number_tip.setText("\nPara garantizarquelacuenta receptora sea consistente con la persona concédula de identidad, la cuenta RUT no admite modificación, se puede elegir otra cuenta bancaria para recibir el pago.");
                    tv_account_number_tip.setTextColor(Color.parseColor("#FFB307"));
                    Log.e("----","006");
                } else {
                    tv_account_number_tip.setVisibility(View.GONE);
                }
            }
        });

    }

    private void hideErrTips() {
        tv_bank_name_err.setVisibility(View.GONE);
        tv_account_number_err.setVisibility(View.GONE);
        number_line.setBackgroundColor(Color.parseColor("#33000000"));
        bank_line.setBackgroundColor(Color.parseColor("#33000000"));
        Log.e("----","03");
    }

    private void getZiLiPageUserFullInfo(boolean isInit) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("custId", ZiLiPageUserDataBean.getInstance().getCustomerId());
        fatherActivity.showLoading();
        kycModle.getZiLiPageUserFullInfo(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                CapitalInforActivity capitalInforActivity = (CapitalInforActivity) getActivity();
                if (capitalInforActivity != null) {
                    capitalInforActivity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                JSONObject jsonObject = new JSONObject(data);
                                if (kycModle.isSuccess(jsonObject)) {
                                    JSONObject dataJsonObject = jsonObject.optJSONObject("data");
                                    String nationalId = dataJsonObject.optString("nationalId");
                                    if (nationalId != null) {
                                        mNationalId = nationalId;
                                        String showNationalId = nationalId.substring(0,nationalId.length() -1);
                                        et_account_number.setText(showNationalId);
//                                        tv_tip.setText("");
                                    }
                                    if (isInit) {
                                        checkAccountNumber();
                                    }

                                } else {
                                    T.showShort(getActivity(), kycModle.getStringToJson(jsonObject, "msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
                }
                fatherActivity.hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                fatherActivity.hideLoading();
            }
        });
    }

    private void dealWithSubData() {
        Map<String, String> params = new HashMap<String, String>();
        //      params.put("bankId", "");
        params.put("bankCode", bankCode);
        Log.e("----bankCode",bankCode);
        params.put("accountType", accountType);
        Log.e("----accountType",accountType);
        if (et_account_type.getText().equals("RUT")
                && et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
            Log.e("----mNationalId",mNationalId);
            Log.e("----et_account_number",et_account_number.getText().toString());
            if (!TextUtils.isEmpty(mNationalId)) {
                params.put("accountNumber", mNationalId);
                Log.e("----mNationalId",mNationalId);
            } else {
                params.put("accountNumber", et_account_number.getText().toString());
                Log.e("----et_account_number",et_account_number.getText().toString());
            }
        } else {
            params.put("accountNumber", et_account_number.getText().toString());
        }
//                params.put("accountNumber", et_account_number.getText().toString());
        params.put("scenes", "info");
        Log.e("----params 2>>--" , new Gson().toJson(params));
        fatherActivity.showLoading();
        LoanModle.Companion.getInstant().bankbindAccount(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                LogUtils.logE("final success1>" + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    Log.e("----jsonObject",jsonObject.toString());
                    if (kycModle.getStringToJson(jsonObject, "code").equals("0000")) {
                        doFinish();
                    } else {
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                ToastUtils.showShort(getActivity(), kycModle.getStringToJson(jsonObject, "msg"));
                                Log.e("----","err1");
                            }
                        });

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fatherActivity.hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                LogUtils.logE("final fail>" + e);
                fatherActivity.hideLoading();
            }
        });
    }



    private void checkAccountNumber() {
        if (et_account_type.getText().equals("RUT") &&
                et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
            et_account_number.setEnabled(false);
            et_account_number.setTextColor(Color.parseColor("#999999"));
            setDefaultBankCode();
            et_account_number.setInputType(InputType.TYPE_CLASS_TEXT);
            getZiLiPageUserFullInfo(false);
//            tv_tip.setVisibility(View.VISIBLE);
//            lly_bottom_tips.setVisibility(View.GONE);

        } else {

//            tv_tip.setVisibility(View.GONE);
//            lly_bottom_tips.setVisibility(View.VISIBLE);
            et_account_number.setEnabled(true);
            et_account_number.setTextColor(Color.parseColor("#000000"));
            et_account_number.setTextColor(Color.parseColor("#333333"));
            if (et_account_type.getText().equals("Cuenta ahorro")
                    || et_account_type.getText().equals("Cuenta corriente")
                    || et_account_type.getText().equals("Vista")) {
                et_account_number.setFilters(new InputFilter[]{new InputFilter.LengthFilter(20)});
                et_account_number.setInputType(InputType.TYPE_CLASS_NUMBER);
                et_account_number.setHint("8-20 dígitos");
            } else if (et_account_type.getText().equals("RUT")) {
                Log.e("----1","1111");
                et_account_number.setInputType(InputType.TYPE_CLASS_TEXT);
                noChinese(et_account_number);
                et_account_number.setFilters(new InputFilter[]{new InputFilter.LengthFilter(9)});
                et_account_number.setHint("7-9 dígitos");
            }

        }
        if (et_account_type.getText().equals("RUT") &&
                et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
            tv_account_number_tip.setVisibility(View.VISIBLE);
            tv_account_number_tip.setText("\nPara garantizarquelacuenta receptora sea consistente con la persona concédula de identidad, la cuenta RUT no admite modificación, se puede elegir otra cuenta bancaria para recibir el pago.");
            tv_account_number_tip.setTextColor(Color.parseColor("#FFB307"));
            Log.e("----","006");
        } else {
            tv_account_number_tip.setVisibility(View.GONE);

        }
    }

    class BankInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            if (dstart == 0 && source.length() > 0 && source.charAt(0) == ' ') {

                return "";
            }


            int keep = 20 - (dest.length() - (dend - dstart));
            if (keep <= 0) {

                return "";
            } else if (keep >= end - start) {

                return null;
            }
            return null;
        }

    }

    class RutInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

            if (dstart == 0 && source.length() > 0 && source.charAt(0) == ' ') {

                return "";
            }


            int keep = 9 - (dest.length() - (dend - dstart));
            if (keep <= 0) {

                return "";
            } else if (keep >= end - start) {

                return null;
            }
            return null;
        }

    }

    private void doFinish() {
        Map<String, String> params = new HashMap<String, String>();
        fatherActivity.showLoading();
        LoanModle.Companion.getInstant().finishPersonalInfo(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                LogUtils.logE("finishPersonalInfo success 2>" + data);
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (kycModle.getStringToJson(jsonObject, "code").equals("0000")) {
                        kycModle.getZiLiPageUserFullInfo(params, new HttpCallback() {
                            @Override
                            public void onSuccess(@NonNull String data) {
                                try {

                                    LogUtils.logE("link update user info data>"+data);
                                    if (kycModle.isSuccess(jsonObject)) {
                                        PointMgr.INSTANCE.sendEvent("cl_xuanz_yh_name_5");
                                        Log.e("PointMgr.INSTANCE.sendEvent", "cl_xuanz_yh_name_5");
                                        goMain(data);

                                    } else {
                                        T.showShort(getActivity(), kycModle.getStringToJson(jsonObject, "msg"));
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFaill(@NonNull String e) {

                            }
                        });
                    } else {
                        ToastUtils.showShort(getActivity(), kycModle.getStringToJson(jsonObject, "msg"));
                        Log.e("----","err2");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fatherActivity.hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                LogUtils.logE("final fail>" + e);
                fatherActivity.hideLoading();
            }
        });
    }

    private void goMain(String jsonObject) {

        CapitalInforActivity capitalInforActivity = (CapitalInforActivity) getActivity();
        if (capitalInforActivity != null) {

            if(!TextUtils.isEmpty(jsonObject)){
                capitalInforActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            LogUtils.logE("history info>jObject");
                            ZiLiPageUserDataBean.getInstance().setRewrite("N");
                            SaveZiLiPageTool saveZiLiPageTool = new SaveZiLiPageTool(BaseApplication.getInstance());
                            ZiLiPageUserDataBean userDataBean = new Gson().fromJson(saveZiLiPageTool.getKeyValue("user_info"), ZiLiPageUserDataBean.class);
                            userDataBean.setRewrite("N");
                            JSONObject ziliJsonObject = new JSONObject(new Gson().toJson(userDataBean));
                            LogUtils.logE("history info>ziliJsonObject---"+ziliJsonObject.toString());
                            ZiLiPageUserDataBean.getInstance().setData(ziliJsonObject, BaseApplication.getInstance());
//                    ZiLiPageUserDataBean.getInstance().setData(new JSONObject(jsonObject), BaseApplication.getInstance());
                            EventBus.getDefault().post(new UpdateUserEvent());

                            Intent resultIntent = new Intent();
                            resultIntent.putExtra("showPer", true);
                            capitalInforActivity.setResult(Activity.RESULT_OK, resultIntent);
                        } catch (JSONException e) {
                            throw new RuntimeException(e);
                        }
                    }
                });
            }
            SharedPreferences sharedPreferences = getActivity().getSharedPreferences("firstTime", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("firstTime","true");
            editor.commit();
            //处理绑定银行卡后，提交成功后，跳到登录页的问题，需要注意跳转后是否是登录后的首页，返回有没有异常
            Intent intent = new Intent(capitalInforActivity, MainActivity.class);
            startActivity(intent);

            capitalInforActivity.finish();

        }
    }

    @Override
    public void initData() {

    }

    public void getZiLiPagePayBankList() {
        if (bankJa != null && bankJa.length() > 0) {
            showSelectBank(bankJa);
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        fatherActivity.showLoading();
        kycModle.getZiLiPagePayBankList(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (kycModle.isSuccess(jsonObject)) {
                        JSONArray dataJa = jsonObject.optJSONArray("data");
                        if (dataJa != null) {
                            showSelectBank(dataJa);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fatherActivity.hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                T.showShort(getContext(), e);
                fatherActivity.hideLoading();
            }
        });
    }

    private void setDefaultBankCode() {
        Map<String, String> params = new HashMap<String, String>();
        fatherActivity.showLoading();
        kycModle.getZiLiPagePayBankList(params, new HttpCallback() {
            @Override
            public void onSuccess(@NonNull String data) {
                try {
                    JSONObject jsonObject = new JSONObject(data);
                    if (kycModle.isSuccess(jsonObject)) {
                        JSONArray dataJa = jsonObject.optJSONArray("data");
                        if (dataJa != null) {
                            CapitalInforActivity capitalInforActivity = (CapitalInforActivity) getActivity();
                            if (capitalInforActivity != null) {
                                capitalInforActivity.runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        List<SingleSelectBean> selectBeanList = new ArrayList<>();
                                        for (int i = 0; i < dataJa.length(); i++) {
                                            JSONObject jsonObject = dataJa.optJSONObject(i);
                                            if (kycModle.getStringToJson(jsonObject,
                                                    "bankName").equals("Banco Estado (Banco del Estado de Chile)")) {
                                                bankCode = kycModle.getStringToJson(jsonObject, "bankCode");
                                                LogUtils.logE("bankCode:"+bankCode);
                                            }
                                        }
                                    }
                                });
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                fatherActivity.hideLoading();
            }

            @Override
            public void onFaill(@NonNull String e) {
                T.showShort(getContext(), e);
                fatherActivity.hideLoading();
            }
        });
    }

    private void selectZiLiPageTipoDeCuenta() {
        List<SingleSelectBean> selectBeanList = new ArrayList<>();
        List<String> values = new ArrayList<>();
        values.add("Cuenta ahorro");
        values.add("Cuenta corriente");
        values.add("Vista");
        values.add("RUT");
//        if (et_bank_name.getText().equals("Banco Estado (Banco del Estado de Chile)")) {
//            values.add("RUT");
//        }
        for (int i = 0; i < values.size(); i++) {
            SingleSelectBean singleSelectBean = new SingleSelectBean();
            singleSelectBean.setId(i);
            singleSelectBean.setText(values.get(i));
            singleSelectBean.setCheck(false);
            selectBeanList.add(singleSelectBean);
        }
        showProfession(selectBeanList, 2, "Tipo de cuenta");//bankName
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        LogUtils.logE("-kyc link -onHiddenChanged--hidden:"+hidden);
        if (!hidden) {
            et_account_type.setText("RUT");
            accountType = "3";
            et_bank_name.setText("Banco Estado (Banco del Estado de Chile)");
            getZiLiPageUserFullInfo(true);
            setDefaultBankCode();
        }
    }

    private void showSelectBank(JSONArray dataJa) {
        this.bankJa = dataJa;
        CapitalInforActivity capitalInforActivity = (CapitalInforActivity) getActivity();
        if (capitalInforActivity != null) {
            capitalInforActivity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    List<SingleSelectBean> selectBeanList = new ArrayList<>();
                    for (int i = 0; i < dataJa.length(); i++) {
                        JSONObject jsonObject = dataJa.optJSONObject(i);
                        SingleSelectBean selectBean = new SingleSelectBean();
                        selectBean.setText(kycModle.getStringToJson(jsonObject, "bankName"));
                        selectBean.setCode(kycModle.getStringToJson(jsonObject, "bankCode"));
                        selectBean.setId(i);
                        selectBean.setCheck(false);
                        selectBeanList.add(selectBean);
                    }
                    showProfession(selectBeanList, 1, "Nombre del banco");//bankName
                }
            });
        }

    }

    private void showProfession(List<SingleSelectBean> dataList, int key, String title) {
        SingleSelectDialogView dialogView = new SingleSelectDialogView(getActivity(), view, title);
        dialogView.setSingleSelectListener(new SingleSelectDialogView.SingleSelectListener() {
            @Override
            public void checked(SingleSelectBean s) {
                if (key == 1) {
                    if (et_bank_name.getText() == s.getText()) {
                        dialogView.dismiss();
                        activityListener.sendValue("beLight");
                        return;
                    } else {
                        et_bank_name.setText(s.getText());
                        bankCode = s.getCode();
                        et_account_type.setText("Cuenta ahorro");
                        setAccountType();
                        et_account_number.setHint("Seleccione su región");
                    }
                } else if (key == 2) {
                    if (et_account_type.getText() == s.getText()) {
                        dialogView.dismiss();
                        activityListener.sendValue("beLight");
                        return;
                    } else {
                        et_account_type.setText(s.getText());
//                        accountType = String.valueOf(s.getId());
                        setAccountType();
                    }
                }
                et_account_number.setText(null);
                checkAccountNumber();
                dialogView.dismiss();
                activityListener.sendValue("beLight");
            }
            @Override
            public void closeDialog(){
                dialogView.dismiss();
                activityListener.sendValue("beLight");
            }
        });
        dialogView.showSingleSelectDialog(activity, dataList);
        activityListener.sendValue("beDark");
    }

    private void setAccountType() {
        if (!TextUtils.isEmpty(et_account_type.getText())) {
            if (et_account_type.getText().equals("Cuenta ahorro")) {
                accountType = "1";
            } else if (et_account_type.getText().equals("Cuenta corriente")) {
                accountType = "0";
            } else if (et_account_type.getText().equals("Vista")) {
                accountType = "2";
            } else if (et_account_type.getText().equals("RUT")) {
                accountType = "3";
            }
        }
    }

    private void close() {
        if (getActivity().getCurrentFocus() == null) {
            return;
        }

        ((InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }

    private class CommonTextWatcher implements TextWatcher {
        private TextView errText;

        private EditText editText;

        public CommonTextWatcher(EditText editText, TextView errText) {
            this.errText = errText;
            this.editText = editText;
        }

        @Override
        public void beforeTextChanged(CharSequence charSequence, int start, int before, int count) {

        }

        @Override
        public void onTextChanged(CharSequence charSequence, int start, int before, int count) {

            requireActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    String trimmedText = charSequence.toString().trim();


                    if (!trimmedText.isEmpty()) {
                        clearEditTextError();
                    }


                    if (startsWithSpace(charSequence)) {

                        editText.setText(trimmedText);
                        editText.setSelection(trimmedText.length());
                    } else {
                        clearEditTextError();
                    }
                }
            });
        }

        @Override
        public void afterTextChanged(Editable editable) {

        }

        private void clearEditTextError() {

            errText.setVisibility(View.GONE);
        }

        private boolean startsWithSpace(CharSequence charSequence) {

            return charSequence.length() > 0 && charSequence.charAt(0) == ' ';
        }
    }

    @Override
    public void onPause(){
        super.onPause();
        fatherActivity.hideLoading();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        PointMgr.INSTANCE.sendEvent("bank_account_info_no");
        Log.e("PointMgr.INSTANCE.sendEvent", "bank_account_info_no");
    }
    private void noChinese(EditText editText){
        editText.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int i2, int i3) {
                for (int i = start; i < end; i++) {
                    if (Character.UnicodeBlock.of(charSequence.charAt(i)) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) {
                        return "";
                    }
                }
                return null;
            }
        }});
    }
}
